﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace ITAP.Core.Utils
{
    public class Archiver
    {
        public static void Zip(Stream uncompressedStream, Stream outputCompressedStream)
        {
            MemoryStream internalZippedStream = new MemoryStream();

            uncompressedStream.Seek(0, SeekOrigin.Begin);
            ZipOutputStream zipOutputStream = new ZipOutputStream(internalZippedStream);

            ZipEntryFactory factory = new ZipEntryFactory(DateTime.Now);
            ZipEntry entry = factory.MakeFileEntry("SHACHLO");

            
            entry.Size = uncompressedStream.Length;
      
            zipOutputStream.PutNextEntry(entry);

            byte[] buffer = new byte[(int)uncompressedStream.Length];
            uncompressedStream.Read(buffer, 0, buffer.Length);
            zipOutputStream.Write(buffer, 0, buffer.Length);        
            zipOutputStream.CloseEntry();


            zipOutputStream.Flush();

            zipOutputStream.Finish();
                       
            buffer = new byte[(int)internalZippedStream.Length];
            internalZippedStream.Seek(0, SeekOrigin.Begin);
            internalZippedStream.Read(buffer, 0, buffer.Length);            
            outputCompressedStream.Write(buffer, 0, buffer.Length);
            zipOutputStream.Close();
        }

        public static void UnZip(Stream compressedStream, Stream outputUncompressedStream)
        {
            
            ZipInputStream zipInputStream = new ZipInputStream(compressedStream);
            
            ZipEntry entry = zipInputStream.GetNextEntry();
            if (entry != null)
            {
                byte[] compressedBytes = new byte[(int)entry.Size];
                int size;
                while (true)
                {
                    size = zipInputStream.Read(compressedBytes, 0, compressedBytes.Length);
                    if (size > 0)
                        outputUncompressedStream.Write(compressedBytes, 0, size);
                    else
                        break;
                }
            }
            outputUncompressedStream.Seek(0, SeekOrigin.Begin);
            zipInputStream.Close();
        }
    }
}
